package com.example.fashion.android.NewWorkCommunication.activity;


import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.SparseArray;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.example.fashion.android.NewWorkCommunication.adapter.CharAdapter;
import com.example.fashion.android.R;
import com.example.fashion.android.base.BaseActivity.BaseActivity;
import com.example.fashion.android.entity.CharInfo;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.util.Date;

public class IMActivity extends BaseActivity {
    RecyclerView mRecyclerView;
    EditText mMessageInfo;
    Button mSend;


    //要连接的服务端IP地址
    private static final String IP_ADDRESS = "192.168.100.36";
    //要连接的服务端对应的监听端口
    private static final int PORT = 9876;

    private Socket mSocket;

    private SparseArray<CharInfo> mMessageList;
    private CharAdapter mCharAdapter;

    //接收线程发送过来信息，并用TextView显示
    public Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            mMessageList.put(mMessageList.size(),new CharInfo(0,msg.obj.toString(),new Date(),msg.arg1));
            mCharAdapter.notifyDataSetChanged();
            mRecyclerView.smoothScrollToPosition(mMessageList.size()-1);
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_im);
    }


    @Override
    public void initView() {
        setSystemTitleName("聊天室");
        mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);  //聊天记录列表
        mMessageInfo = (EditText) findViewById(R.id.msg_et);        //聊天信息编辑框
        mSend = (Button) findViewById(R.id.btn_send);        //聊天信息编辑框

    }


    @Override
    public void initData() {
        //初始化适配器
        mRecyclerView.setLayoutManager(new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL));
        mMessageList = new SparseArray();
        mCharAdapter = new CharAdapter(this, mMessageList);
        mRecyclerView.setAdapter(mCharAdapter);

        initEvent();
    }

    /**
     * 初始化事件
     */
    public void initEvent() {
        //监听文本变化
        mMessageInfo.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (TextUtils.isEmpty(mMessageInfo.getText().toString())) {
                    mSend.setVisibility(View.GONE);
                } else {
                    mSend.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        //点击发送
        findViewById(R.id.btn_send).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new Thread() {
                    @Override
                    public void run() {
                        try {
                            //发送消息
                            sendMessage();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }.start();

            }
        });
    }

    /**
     * 发送消息
     */
    public void sendMessage() throws Exception {
        Message message = mHandler.obtainMessage();
        message.obj = mMessageInfo.getText().toString();
        message.arg1 = CharInfo.MESSAGE_TYPE_REPLY;
        mHandler.sendMessage(message);

        //与服务端建立连接
        if(mSocket==null||mSocket.isClosed()||mSocket.isConnected()){
            mSocket = new Socket(IP_ADDRESS, PORT);
        }

        //建立连接后就可以往服务端写数据了
        Writer writer = new OutputStreamWriter(mSocket.getOutputStream(), "UTF-8");
        writer.write(mMessageInfo.getText().toString());
        writer.write("eof\n");
        writer.flush();
        //写完以后进行读操作
        BufferedReader br = new BufferedReader(new InputStreamReader(mSocket.getInputStream(), "UTF-8"));
        //设置超时间为10秒
        mSocket.setSoTimeout(10 * 1000);
        StringBuffer sb = new StringBuffer();
        String temp;
        int index;
        try {
            while ((temp = br.readLine()) != null) {
                if ((index = temp.indexOf("eof")) != -1) {
                    sb.append(temp.substring(0, index));
                    break;
                }
                sb.append(temp);
            }
        } catch (SocketTimeoutException e) {
            System.out.println("数据读取超时。");
        }

        Message message2 = mHandler.obtainMessage();
        message2.obj = sb.toString();
        message2.arg1 = CharInfo.MESSAGE_TYPE_RECEIVE;
        mHandler.sendMessage(message2);

        writer.close();
        br.close();
        mSocket.close();
    }

    @Override
    protected void clear() {

    }
}
